package com.me.mysqladmin.dao.impl;

import java.sql.SQLException;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.sql.RowSet;

import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

import com.me.mysqladmin.dao.TableFieldDAO;
import com.me.mysqladmin.entity.Location;
import com.me.mysqladmin.entity.TableField;
import com.me.mysqladmin.util.RowSetUtil;

@Repository("tableFieldDAO")
public class TableFieldDAOImpl extends BaseDAOImpl<TableField> implements TableFieldDAO {
	// 集中定义SQL语句
	private static String QUERY_PRIMARY_KEY = "SELECT k.column_name "
			+ "FROM information_schema.table_constraints t "
			+ "JOIN information_schema.key_column_usage k "
			+ "USING (constraint_name,table_schema,table_name) "
			+ "WHERE t.constraint_type='PRIMARY KEY' "
			+ "AND t.table_schema=? "
			+ "AND t.table_name=?";
	
	private static String DESC_TABLE = "DESC ";

	/**
	 * 将结果集转换成对应的实体集
	 */
	@Override
	protected List<TableField> toEntities(RowSet rs) {
		return RowSetUtil.toEntiyList(rs, TableField.class);
	}
	

	/**
	 * 查询一张表的字段信息（Map表示）
	 * @param loc
	 * @return
	 */
	@Override
	public List<Map<String, Object>> queryFieldMap(Location loc){
		String databaseName = loc.getDatabaseName();
		String tableName = loc.getTableName();
		try {
			return queryMap(DESC_TABLE + databaseName + "." + tableName);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return Collections.emptyList();
	}
	
	/**
	 * 查询一张表的主键名
	 */
	@Override
	public String queryPrimaryKeyCol(Location loc) {
		String databaseName = loc.getDatabaseName();
		String tableName = loc.getTableName();
		try {
			List<Map<Integer, Object>> list = querySpecificCols(QUERY_PRIMARY_KEY, 1, databaseName, tableName);
			Assert.notEmpty(list);
			return (String) list.get(0).get(1);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return "id";
	}
}
